<?php
Base::loadFile ( 'image', 'lib' );
class Watermark extends Image {
	private $_rWater;
	private $_aWater;
	private $_rImage;
	private $_aImage;
	
	public function setWater($sFile = null) {
		if ($sFile) {
			$this->_rWater = parent::open ( $sFile );
			$this->_aWater = parent::getInfo ( $sFile );
		} else {
			$this->_rWater = parent::open ( ROOT . '/' . Base::getConf ( 'image.watermark' ) );
			$this->_aWater = parent::getInfo ( ROOT . '/' . Base::getConf ( 'image.watermark' ) );
		}
	}
	
	public function setImage($sFile) {
		$this->_rImage = parent::open ( $sFile );
		$this->_aImage = parent::getInfo ( $sFile );
	}
	
	public function mark($sImage, $sWater = null, $sFile = null) {
		$this->setWater ( $sWater );
		$this->setImage ( $sImage );
		if ($this->_aImage ['width'] > $this->_aWater ['width'] && $this->_aImage ['height'] > $this->_aWater ['height']) {
			$iType = intval ( Base::getConf ( 'image.watermark_type' ) );
			if ($iType == 0) {
				$iType = 9;
			}
			if ($iType < 4) {
				$iY = 0;
			} elseif ($iType < 7) {
				$iY = ($this->_aImage ['height'] - $this->_aWater ['height']) / 2;
			} else {
				$iY = $this->_aImage ['height'] - $this->_aWater ['height'];
			}
			if ($iType % 3 == 1) {
				$iX = 0;
			} elseif ($iType % 3 == 2) {
				$iX = ($this->_aImage ['width'] - $this->_aWater ['width']) / 2;
			} else {
				$iX = $this->_aImage ['width'] - $this->_aWater ['width'];
			}
			imagealphablending ( $this->_rWater, true );
			$iPct = intval ( Base::getConf ( 'image.watermark_pct' ) );
			if ($iPct == 0) {
				$iPct = 30;
			}
			
			if ($this->_aWater ['type'] == 'gif') {
				imagealphablending ( $this->_rWater, true );
				@imagecopymerge ( $this->_rImage, $this->_rWater, $iX, $iY, 0, 0, $this->_aWater ['width'], $this->_aWater ['height'], $iPct );
			} else {
				@imagecopy ( $this->_rImage, $this->_rWater, $iX, $iY, 0, 0, $this->_aWater ['width'], $this->_aWater ['height'] );
			}
			if ($sFile) {
				@imagejpeg ( $this->_rImage, $sFile, 100 );
			} else {
				@imagejpeg ( $this->_rImage, $sImage, 100 );
			}
			imagedestroy ( $this->_rWater );
			imagedestroy ( $this->_rImage );
			return true;
		} else {
			return false;
		}
	}
}